*****************pull Flags from personnel records*********************

use pid_pde e1sfpars01 e1sfpars02 e1dtsfpa01 e1dtsfpa02 using  "$data_in/Personnel", clear
drop if mi(e1sfpars01)
bys pid: gen n = _n
rename (e1dtsfpa01 e1sfpars01 e1dtsfpa02 e1sfpars02) (date_flag1 flag1 date_flag2 flag2)
reshape long date_flag flag, i(pid_pde n) j(num)
drop if mi(flag)
drop n num
duplicates drop

replace date_flag = dofc(date_flag)
format date_flag %d
bys pid_pde: gen n = _n
summ n 
local max_r `r(max)'
reshape wide flag date_flag, i(pid_pde) j(n)
merge 1:m pid_pde using "$data_out/provider_propensity", keep(2 3) nogen
keep if officer == 0 & service == "A"



gen any_flag = 0
gen any_flag2 = 0
gen substance_flag = 0
gen substance_flag2 = 0
gen adverse_flag = 0
gen adverse_flag2 = 0
gen crime_flag = 0
gen crime_flag2 = 0

forval i = 1/`max_r' {
qui replace any_flag = 1 if inrange(date_flag`i', encdate, encdate + 365) & date_flag`i' <.
qui replace any_flag2 = 1 if inrange(date_flag`i', encdate, encdate + 730) & date_flag`i' <.
qui replace substance_flag = 1 if inrange(date_flag`i', encdate, encdate + 365) & date_flag`i' <. & inlist(flag`i', "U", "V")
qui replace substance_flag2 = 1 if inrange(date_flag`i', encdate, encdate + 730) & date_flag`i' <. & inlist(flag`i', "U", "V")
qui replace adverse_flag = 1 if inrange(date_flag`i', encdate, encdate + 365) & date_flag`i' <. & inlist(flag`i', "A", "H")
qui replace adverse_flag2 = 1 if inrange(date_flag`i', encdate, encdate + 730) & date_flag`i' <. & inlist(flag`i', "A", "H")
qui replace crime_flag = 1 if inrange(date_flag`i', encdate, encdate + 365) & date_flag`i' <. & inlist(flag`i', "M")
qui replace crime_flag2 = 1 if inrange(date_flag`i', encdate, encdate + 730) & date_flag`i' <. & inlist(flag`i', "M")

}

 
 save "$data_out/Flags", replace





